package com.boot.mall.order.mq;

import com.boot.common.constant.MqDestinationConstant;
import org.apache.activemq.ScheduledMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;

import javax.jms.*;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;

@Service
public class JmsProducer {

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    /**
     * 发送延迟消息
     * @param message
     * @param timeSecond
     */
    public void delaySendMessage(Object message, Long timeSecond){
        timeSecond = timeSecond * 1000L;
        // 1.创建连接工厂
        ConnectionFactory connectionFactory = jmsMessagingTemplate.getConnectionFactory();
        try {
            // 2.创建连接
            Connection connection = connectionFactory.createConnection();
            // 3.连接启动
            connection.start();
            // 4.创建会话session，设置不开启事务，签收方式为自动签收
            Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
            // 5.创建目的地，消息队列
            Queue queue = session.createQueue(MqDestinationConstant.ORDER_QUEUE);
            // 6.创建生产者
            MessageProducer producer = session.createProducer(queue);
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);  //开启持久化
            // 7.创建一个延时消息
            ObjectMessage objectMessage = session.createObjectMessage((Serializable) message);
            objectMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY,timeSecond);
            // 8.发送消息
            producer.send(objectMessage);
            // 9.关闭资源
            producer.close();
            session.close();
            connection.close();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

}
